package com.gydz.gydzbaseframeworkboot.Common.utils;

import java.lang.reflect.Field;
import java.util.List;

public class FieldConverter {

    public static <T> List<T> convertMinusOneToNull(List<T> list) {
        for (T obj : list) {
            convertObjectFields(obj);
        }
        return list;
    }

    private static <T> void convertObjectFields(T obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (field.getType().equals(int.class) && field.getInt(obj) == -1) {
                    field.set(obj, 0); // int 类型不能设置为 null，可以设置为默认值 0 或其他合适值
                } else if (field.getType().equals(Integer.class) && field.get(obj) != null && ((Integer) field.get(obj)) == -1) {
                    field.set(obj, null);
                } else if (field.getType().equals(long.class) && field.getLong(obj) == -1L) {
                    field.set(obj, 0L); // long 类型不能设置为 null，可以设置为默认值 0L 或其他合适值
                } else if (field.getType().equals(Long.class) && field.get(obj) != null && ((Long) field.get(obj)) == -1L) {
                    field.set(obj, null);
                } else if (field.getType().equals(String.class) && field.get(obj) != null && field.get(obj).equals("-1")) {
                    field.set(obj, null);
                }else if (field.getType().equals(Short.class) && field.get(obj) != null && ((Short) field.get(obj)) == -1) {
                    field.set(obj, null);
                }else if (field.getType().equals(Byte.class) && field.get(obj) != null && ((Byte) field.get(obj)) == -1) {
                    field.set(obj, null);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

